const bcrypt = require('bcryptjs')
const { getUserInfo } = require('../service/user.service')
const {
 userFormateError,
 userAlreadyExited,
 userRegisterError,
 userDoesNotExits,
 userLoginError,
 invalidPassword
} = require('../constant/error.type')

const userValidator = async (ctx, next) => {
 const { user_name, password } = ctx.request.body
 if (!user_name || !password) {
  console.error('用户名或密码为空', ctx.request.body)
  ctx.app.emit('error', userFormateError, ctx)
  return;
 }
 await next()
}

const varifyUser = async (ctx, next) => {
 const { user_name } = ctx.request.body
 try {
  const res = await getUserInfo({ user_name })
  if (res) {
   console.error('用户名已经存在', user_name)
   ctx.app.emit('error', userAlreadyExited, ctx)
   return;
  }
 } catch (err) {
  console.error('获取用户信息错误', err)
  ctx.app.emit('error', userRegisterError, ctx)
  return;
 }
 await next()
}

const crpytPassword = async (ctx, next) => {
 const { password } = ctx.request.body
 const salt = bcrypt.genSaltSync(10)
 const hash = bcrypt.hashSync(password, salt)
 ctx.request.body.password = hash
 await next()
}

const varifyLogin = async (ctx, next) => {
 const { user_name, password } = ctx.request.body
 const res = await getUserInfo({ user_name })
 try {
  if (!res) {
   console.error('用户名不存在', user_name)
   return ctx.app.emit('error', userDoesNotExits, ctx)
  }
  if (!bcrypt.compareSync(password, res.password)) {
   console.error('用户密码错误', password)
   return ctx.app.emit('error', invalidPassword, ctx)
  }
 } catch (err) {
  console.error(err)
  return ctx.app.emit('error', userLoginError, ctx)
 }
 await next()
}

module.exports = {
 userValidator,
 varifyUser,
 crpytPassword,
 varifyLogin
}